<script setup lang="ts">
import { type BlogItem, type BlogTagItem, type PageData, type ResponseData } from '~/types';
import {VsLoadingFn, VsPagination} from "vuesax-alpha";
import notFoundIcon from '~/assets/svg/404.svg'
import {CardContainer,CardBody,CardItem} from "~/components/ui/card-3d";
import {type ScrollTrigger} from "gsap/ScrollTrigger";
import {useScrollTrigger as scrollTrigger} from "#gsap";
import {darkTheme, type NElement} from "naive-ui";
import CardSpotlight from "~/components/ui/CardSpotlight.vue";
import {useColorMode} from "@vueuse/core";
import {useListAnimate} from "~/server/utils";


const myBlogs = ref<BlogItem[]>([]);
const total = ref(0);
const router = useRouter();
const dataLoading = ref(true)
const homeContainer = ref<HTMLElement>()
const blogItemContainer = ref<typeof CardContainer[]>()
const pagination = ref<InstanceType<typeof VsPagination>>()
const currentPage = ref(1)
const size = ref(10)
const isDark = computed(() => useColorMode().value == "dark");
const getContentMain:()=>HTMLElement = inject('getContentEl') as any

//   开启列表动画
const { $gsap:gsap} = useNuxtApp();
gsap.registerPlugin(scrollTrigger);
type TimeLine = gsap.core.Timeline
let timelines: {value: TimeLine,el:HTMLElement}[] = []
const typeList = [ "default" ,"primary", "info", "success","warning","error"] as const
type TagType = typeof typeList[number]
const loadingBar = useLoadingBar();
async function getBlogs() {
  // timelines.forEach((tl)=>{
  //   tl.value?.to(tl.el,{},0)
  //   tl.value?.kill()
  // });
  timelines = []
  const params = {
    page: currentPage.value,
    size: size.value,
    blogType: 1
  }
  dataLoading.value = true;
  const loadingFn = VsLoadingFn({
    target: '#index-home-container',
    type: 'circles',
    // text: '玩命加载中',
    scale: '1.2',
    // background: 'rgba(0,0,0,0.1)'
  })
  loadingBar?.start()
  $fetch('/api/blogs/getBlogs',{
    params,
  }).then(res => {
    const resData = res as unknown as ResponseData<PageData<BlogItem[]>>;
    // console.log(resData)
    total.value = resData.data.total;
    myBlogs.value = resData.data.list || [];
    loadingBar?.finish()
  }).catch(()=> {
    loadingBar.error()
  }).finally(()=> {
    loadingFn.close()
    dataLoading.value = false
    scrollTrigger.refresh()

    const elements:HTMLElement[]|Element[] = blogItemContainer.value?.map((item: typeof CardContainer) => item.$el) || [];
    if (homeContainer.value && elements.length) {
      // const timelines = elements.map(v=> (
      //     {
      //       el: v,
      //       tl: getTl(v)
      //     }
      // ));
      // timelines.forEach(v=> {
      //   v.tl.add(getTween(v.el))
      // })
      const gsap = useNuxtApp().$gsap
      const {startTweenAnimate} = useListAnimate(gsap,elements);
      startTweenAnimate()
    }
  })
  // myBlogs.value = (await useFetch('/api/blog/getBlogs')).data as any;
  //   todo :添加首页插画背景、详情页字数统计、时间等
}
function detailClick(item:BlogItem,discuss=false) {
  router.push({
    path: '/detail',
    query:{
      id: item.id,
      title: item.blogTitle,
      discuss: String(discuss ? 1: 0)
    }
  })
}
function getRandomType():TagType{
  const randomIndex = Math.floor(Math.random()*6)
  return typeList[randomIndex] as TagType
}
function handlePageChange(val:number){
  currentPage.value = val;
  getBlogs()
}
function handleSizeChange(val:number){
  size.value = val;
  currentPage.value = 1
  getBlogs()
}

onMounted(()=> {
  console.log('mounts')
  myBlogs.value =  [];
  nextTick(()=> {
    getBlogs()
  })
})

</script>
<template>
  <n-el class="my-home-container">
    <div class="w-full h-auto">
      <client-only v-if="myBlogs.length>0">
        <div ref="homeContainer" class="h-full w-11/12 m-auto flex flex-wrap gap-6" id="index-home-container">
          <CardContainer ref="blogItemContainer" container-class="2xl:w-[calc(33.3%-1.5em)] lg:w-[calc(50%-3em)] w-full h-1/2 h-80" class="h-full w-full card-item" v-for="item in myBlogs" :key="item.id" >
            <CardBody @click="detailClick(item)"  class="cardBox w-full cursor-pointer flex flex-nowrap p-6 lg:p-10  group/card relative h-full shadow hover:shadow-2xl rounded-xl border border-black/[0.1] bg-gray-50 dark:border-white/[0.2] dark:bg-black dark:hover:shadow-2xl dark:hover:shadow-emerald-500/[0.1]">
              <CardItem :translate-z="100" class="w-1/3 mr-3">
                <n-image lazy class="h-full" object-fit="cover" preview-disabled :src="item.coverUrl"  alt="图片">
                  <template #error>
                    <n-icon :size="100" color="lightGrey">
                      <i class="bx bx-image"></i>
                    </n-icon>
                  </template>
                </n-image>
              </CardItem>
              <div class="flex flex-col flex-auto">
                <CardItem :translate-z="60" class="mb-2" >
                  <vs-button class="btn-chat" type="shadow" @click.stop="detailClick(item,true)">
                    <i class="bx bx-chat" />
                    <span class="span"> {{ item.discussCount }} </span>
                  </vs-button>
                </CardItem>
                <CardItem :translate-z="60" class="flex-auto flex flex-col">
                  <n-h3 class="flex-grow-0 flex-shrink-0">{{item.blogTitle}}</n-h3>
                  <n-el class="text-container flex-auto">
                    <n-p>{{item.blogDesc}}</n-p>
                    <div class="tag-container">
                      <n-space class="items-center">
                        <n-tag :type="getRandomType()" :bordered="false" v-for="tag in item.tagsList.slice(0,2)">
                          <n-ellipsis style="max-width: 4.2em">
                            {{tag.tagName}}
                          </n-ellipsis>
                          <template #avatar>
                            <n-avatar
                                v-if="tag.tagImg"
                                :src="tag.tagImg"
                            >
                              <template #fallback>
                                <i class='bx bxs-purchase-tag'></i>
                              </template>
                            </n-avatar>
                            <i v-else class='bx bxs-purchase-tag'></i>
                          </template>
                        </n-tag>
                        <n-popover trigger="hover"
                                   v-if="item.tagsList && item.tagsList.length>2"
                                   placement="top"
                        >
                          <template #trigger>
                            <n-button text>
                              <i class='bx bxl-flickr'></i>
                            </n-button>
                          </template>
                          <span>
                                <n-space>
                                  <n-tag :type="getRandomType()"  :bordered="false" v-for="tag in item.tagsList.slice(2)">
                                      {{tag.tagName}}
                                    <template #avatar>
                                      <n-avatar
                                          v-if="tag.tagImg"
                                          :src="tag.tagImg"
                                      >
                                        <template #fallback>
                                          <i class='bx bxs-purchase-tag'></i>
                                        </template>
                                      </n-avatar>
                                      <i v-else class='bx bxs-purchase-tag'></i>
                                    </template>
                                  </n-tag>
                                </n-space>
                              </span>
                        </n-popover>
                      </n-space>
                    </div>
                  </n-el>
                </CardItem>
              </div>
            </CardBody>
          </CardContainer>
        </div>
      </client-only>
      <div class="data-empty" v-else-if="!dataLoading">
        <img :src="notFoundIcon" alt="page not found"/>
      </div>
    </div>
    <!--        分页器-->
    <vs-pagination
        ref="pagination"
        class="w-11/12 m-auto text-center mb-8 mt-8 fe-pagination"
        v-model:current-page="currentPage"
        :layout="['total', 'prev', 'pager', 'next', 'jumper', 'sizes']"
        :total="total"
        :page-size="size"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
    />
  </n-el>
</template>


<style lang="scss" scoped>
.text-container{
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  flex: 1 1 auto;
  overflow: hidden;
  .tag-container{
    display: flex;
  }
}
.data-empty{
  width: 60%;
  margin: 0 auto;
}
.fe-pagination{
  justify-content: center;
}
</style>